<template>
  <div>
    <el-button @click="openAdd()" type="primary" plain style="margin-left:10px">添加系列课程</el-button>
    <div style="background:#fff;width:100%;height:100%;margin-top:10px">
      <!-- 全查 -->
      <el-table :data="tableData" style="width: 100%; margin-top: 10px; margin-left: 15px" @selection-change="handleSelectionChange" :header-cell-class-name="'headerBg'">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="subjectCourseTitle" label="系列标题" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="teacherName" label="教师姓名" align="center">
        </el-table-column>
        <el-table-column prop="subjectCourseInfo" label="系列介绍" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="courseStatus" label="课程状态" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.subjectCourseStatus" active-color="#13ce66" inactive-color="#ff4949" active-value="0" inactive-value="1" @change="upSwitch(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350px" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="small" style="background:none;border:0px"><span style="color:#409EFF;" @click="openXiangxi(scope.row)">详情</span></el-button>
            <el-button type="primary" size="small" style="background:none;border:0px"><span style="color:#409EFF;" @click="openCourse(scope.row.id)">分配课程</span></el-button>
            <el-button type="primary" size="small" style="background:none;border:0px"><span style="color:#409EFF;" @click="openXiugai(scope.row)">修改</span></el-button>
            <el-popconfirm class="ml-5" confirm-button-text='确定' cancel-button-text='我再想想' icon="el-icon-info" icon-color="red" title="您确定删除吗？" @confirm="delCourse(scope.row.id)">
              <el-button type="primary" size="small" slot="reference" style="background:none;border:0px"><span style="color:#409EFF;">删除</span></el-button>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination :page-sizes="[5, 10, 15, 20]" :page-size="pages.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pages.total" background :current-page.sync="pages.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
    </div>
    <!-- 添加 -->
    <el-dialog :visible.sync="addButton" width="30%">
      <el-form :model="addForm" ref="addForm" :rules="rules">
        <el-form-item>
          <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
          <span style="margin-left: 20px">系列封面</span>
          <el-upload class="avatar-uploader" action="" style="margin-top: -40px; margin-left: 100px" list-type="picture-card" :show-file-list="false" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img height="148" v-if="seriesImg" :src="seriesImg" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item width="90%" prop="subjectCourseTitle">
          <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
          <span style="margin-left: 20px">系列标题</span>
          <el-input style="width: 90%; margin-left: 20px" v-model="addForm.subjectCourseTitle" placeholder="请输入系列标题" :maxlength="20" show-word-limit clearable></el-input>
        </el-form-item>
        <el-form-item width="90%" prop="subjectCourseInfo">
          <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
          <span style="margin-left: 20px">系列介绍</span>
          <el-input style="width: 90%; margin-left: 20px" v-model="addForm.subjectCourseInfo" placeholder="请输入系列介绍" :maxlength="200" type="textarea" show-word-limit clearable></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="addSeries">保存</el-button>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog :visible.sync="upButton" width="30%">
      <el-form :model="upForm" ref="upForm" :rules="rules">
        <el-form-item class="aaa">
          <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
          <span style="margin-left: 20px">系列封面</span>
          <el-upload class="avatar" action="" style="margin-top: -40px; margin-left: 100px;width:100%" list-type="picture-card" :show-file-list="false" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="seriesImg" :src="seriesImg" height="148">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item width="90%" prop="subjectCourseTitle">
          <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
          <span style="margin-left: 20px">系列标题</span>
          <el-input style="width: 90%; margin-left: 20px" v-model="upForm.subjectCourseTitle" placeholder="请输入系列标题" :maxlength="20" show-word-limit clearable></el-input>
        </el-form-item>
        <el-form-item width="90%" prop="subjectCourseInfo">
          <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
          <span style="margin-left: 20px">系列介绍</span>
          <el-input style="width: 90%; margin-left: 20px" v-model="upForm.subjectCourseInfo" placeholder="请输入系列介绍" :maxlength="200" type="textarea" show-word-limit clearable></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="upSeries">保存</el-button>
    </el-dialog>

    <!-- 选择课程 -->
    <el-dialog :visible.sync="addCourseButton" width="20%">
      <el-tree :data="courseData" :props="defaultProps" node-key="id" show-checkbox ref="tree" :default-expanded-keys="expends" :default-checked-keys="checks" @node-click="handleNodeClick">
      </el-tree>
      <el-button @click="addCourse">保存</el-button>
    </el-dialog>
    <!-- // 详细 -->
    <el-dialog :visible.sync="xiangxiButton" width="30%" style="text-align: left">
      <el-form :model="xiangxiForm">
        <el-form-item prop="courseTitle">
          <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
          <span style="margin-left: 20px">系列标题</span>
          <el-input style="width:80%; margin-left: 20px" v-model="xiangxiForm.subjectCourseTitle" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item prop="courseTitle">
          <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
          <span style="margin-left: 20px">系列介绍</span>
          <el-input style="width: 80%; margin-left: 20px" v-model="xiangxiForm.subjectCourseInfo" :disabled="true"></el-input>
        </el-form-item>
        <el-row>

          <el-col :span="12">
            <el-form-item prop="educationId">
              <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
              <span style="margin-left: 20px">讲　　师</span>
              <el-input style="width: 60%; margin-left: 20px" v-model="xiangxiForm.teacherName" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="seniority">
              <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
              <span style=" margin-left: 20px">课程状态</span>
              <el-input style="width: 60%; margin-left: 20px" v-model="xiangxiForm.subjectCourseStatus" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
          <span style="margin-left: 20px; vertical-align: top">系列封面</span>
          <img :src="'http://101.43.223.224:8765/image/getImageById?id=' + xiangxiForm.subjectImage" style="width: 80%; display: block; vertical-align: top">
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      tableData: [],

      addButton: false,
      upButton: false,
      upForm: {},
      addCourseButton: false,
      expends: [],
      checks: [],
      addForm: {},
      ids: [],
      dictName: "",
      seriesImg: "",
      imgSeries: "",
      pages: {
        // 当前页
        pageNum: 1,
        // 每页几条数据
        pageSize: 5,
      },
      rules: {
        subjectCourseTitle: [
          { required: true, message: "请输入系列标题", trigger: "blur" },
        ],
        subjectCourseInfo: [
          { required: true, message: "请输入系列介绍", trigger: "blur" },
        ],
      },
      courseIds: [],
      courseData: [],
      defaultProps: {
        children: "children",
        label: "dictName",
      },
      addCourseForm: {},
      xiangxiForm: {},
      xiangxiButton: false,
      teacherId: 0,
      teacherRole: "",
      id:0
    };
  },
  mounted() {
    this.id = JSON.parse(localStorage.getItem("user")).id;
    this.teacherRole = JSON.parse(localStorage.getItem("user")).role;
    if(this.teacherRole == 'ROLE_TEACHER'){this.$axios
        .get("/back_course/selectTeacherId", {
          params: {
            userId:this.id
          },
        })
        .then((res) => {
          if ((res.data.flag)) {
            //教师信息表格赋值
          this.teacherId=res.data.data.id
          
          
          }
        })
        .catch((err) => {});}
    this.selectSeries();
  },
  methods: {
    delCourse(id) {
      this.$axios
        .get("backSeriesCourse/delCourse", {
          params: {
            id: id,
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success("删除成功");
            this.selectSeries();
          }
        });
    },
    openXiugai(row) {
      console.log(row);
      this.seriesImg =
        "http://101.43.223.224:8765/image/getImageById?id=" + row.subjectImage;
      console.log(this.seriesImg);
      console.log(row.subjectImage);
      this.selectById(row.id);
      this.upButton = true;
    },
    selectById(id) {
      console.log(id);
      this.$axios
        .get("backSeriesCourse/selectById", {
          params: {
            id: id,
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.upForm = res.data.data;
          }
        });
    },
    openXiangxi(row) {
      this.$axios
        .get("backSeriesCourse/selectById", {
          params: {
            id: row.id,
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.xiangxiForm = res.data.data;
            if (this.xiangxiForm.subjectCourseStatus === "0") {
              this.xiangxiForm.subjectCourseStatus = "启用";
            }
            if (this.xiangxiForm.subjectCourseStatus === "1") {
              this.xiangxiForm.subjectCourseStatus = "禁用";
            }
          }
        });

      this.xiangxiButton = true;
    },
    openCourse(id) {
      this.selectCheck(id);
      this.selectCourse();
      this.addCourseForm.id = id;
      this.addCourseButton = true;
    },
    selectCheck(id) {
      console.log(id);
      this.$axios
        .get("backSeriesCourse/selectCheck", {
          params: {
            id: id,
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.checks = res.data.data;
          }
        });
    },
    selectCourse() {
      this.$axios
        .get("backSeriesCourse/selectDict", {
          params: {
            teacherId: 1,
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.courseData = this.generateTreeData(res.data.data);
          }
        });
    },
    generateTreeData(data, level = 1) {
      let treeData = [];

      for (let i = 0; i < data.length; i++) {
        let node = {
          id: data[i].id,
          dictName: data[i].dictName,
          level: level, // 添加 level 属性
          children: [],
        };

        if (
          data[i].seriesCourseModels &&
          data[i].seriesCourseModels.length > 0 &&
          level < 3
        ) {
          let seriesCourses = data[i].seriesCourseModels;

          for (let j = 0; j < seriesCourses.length; j++) {
            let courseNode = {
              id: seriesCourses[j].id,
              dictName: seriesCourses[j].courseTitle,
              level: level + 1, // 添加 level 属性
            };

            node.children.push(courseNode);
          }
        }

        if (data[i].children && data[i].children.length > 0 && level < 2) {
          node.children = this.generateTreeData(data[i].children, level + 1);
        }

        treeData.push(node);
      }

      return treeData;
    },
    addCourse() {
      const checkedNodes = this.$refs.tree.getCheckedNodes(true); // 获取所有被选中的节点对象数组

      this.courseIds = checkedNodes
        .filter((node) => node.level === 3) // 过滤出第三级节点
        .map((node) => node.id); // 提取第三级节点的id

      this.addCourseForm.courseIds = this.courseIds;
      this.$axios
        .post("/backSeriesCourse/addCourse", this.addCourseForm)
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success("操作成功");
            this.selectSeries();
            this.addCourseButton = false;
          } else if (res.data.code === 500) {
            this.$message.warning("操作失败");
          }
        });
    },
    upSeries() {
      this.$refs["upForm"].validate((valid) => {
        if (valid) {
          const formData = new FormData();
          formData.set("id", this.upForm.id);
          formData.set("subjectImage", this.upForm.subjectImage);
          formData.set("subjectCourseInfo", this.upForm.subjectCourseInfo);
          formData.set("subjectCourseTitle", this.upForm.subjectCourseTitle);
          // 课程图片
          if (this.imgSeries) {
            formData.set("file", this.imgSeries, this.imgSeries.name);
          }

          this.$axios
            .post("/backSeriesCourse/upSeries", formData)
            .then((res) => {
              if (res.data.code === 200) {
                this.upButton = false;
                this.seriesImg = "";
                this.selectSeries();
                this.$message.success("保存成功")
              }
            });
        }
      });
    },
    addSeries() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          const formData = new FormData();
          formData.set(
            "teacherId",
            JSON.parse(localStorage.getItem("user")).id
          );
          // 课程图片
          if (this.imgSeries) {
            formData.set("file", this.imgSeries, this.imgSeries.name);
          }
          for (const key in this.addForm) {
            formData.set(key, this.addForm[key]);
          }
          this.$axios
            .post("/backSeriesCourse/insertSeries", formData)
            .then((res) => {
              if (res.data.code === 200) {
                this.addButton = false;
                this.addForm = {};
                this.selectSeries();
                this.$message.success("添加成功")
              }
            });
        }
      });
    },
    upSwitch(row) {
      this.$axios
        .get("/backSeriesCourse/upSwitch", {
          params: {
            id: row.id,
            subjectCourseStatus: row.subjectCourseStatus,
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.selectSeries();
            if (row.subjectCourseStatus == 1) {
              this.$message.success("已禁用");
            }
            if (row.subjectCourseStatus == 0) {
              this.$message.success("已启用");
            }
          }
        });
    },
    selectSeries() {
      if (this.teacherRole == "ROLE_TEACHER") {
        this.$axios
          .get("/backSeriesCourse/teacherSelectSeries", {
            params: {
              pageNum: this.pages.pageNum,
              pageSize: this.pages.pageSize,
              id:this.id
            },
          })
          .then((res) => {
            if (res.data.code === 200) {
              this.tableData = res.data.data.content;
              this.pages.total = res.data.data.totalSize;
            }
          });
      }
      if (this.teacherRole == "ROLE_ADMIN") {
        this.$axios
          .get("/backSeriesCourse/selectSeries", {
            params: {
              pageNum: this.pages.pageNum,
              pageSize: this.pages.pageSize,
            },
          })
          .then((res) => {
            if (res.data.code === 200) {
              this.tableData = res.data.data.content;
              this.pages.total = res.data.data.totalSize;
            }
          });
      }
    },
    openAdd() {
      this.addButton = true;
    },
    // 图片格式验证
    beforeAvatarUpload(file) {
      //上传图片格式
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是JPG/PNG格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过2MB!");
        return false;
      }
      //赋值
      this.imgSeries = file;
      this.seriesImg = URL.createObjectURL(file);
      //isJPG && isLt2M 自动提交 false 是点击确定后提交
      return false;
    },
    handleSelectionChange(val) {
      this.ids = val.map((v) => v.id);
    },
    // 分页
    handleSizeChange(val) {
      this.pages.pageSize = val;
      this.selectSeries();
    },
    handleCurrentChange(val) {
      this.pages.pageNum = val;
      this.selectSeries();
    },
    handleAvatarSuccess() {},
    handleNodeClick(data) {
      console.log(data);
    },
  },
};
</script>

<style>
.headerBg {
  background: #f8f8f9 !important;
}
</style>
